﻿using System.Web.Mvc;
using System.Collections.Specialized;
using System;
using System.Collections.Generic;
using System.Linq;
using Xoohoo.Extensions;
using Xoohoo.Modules.CMS.Models;

namespace Xoohoo.Modules.CMS.ModelBinders
{
    public class CategoryInputModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            NameValueCollection form = controllerContext.HttpContext.Request.Form;

            Guid tmpGuid;

            Guid? categoryID = null;
            if (form["categoryID"].GuidTryParse(out tmpGuid))
                categoryID = tmpGuid;
            Guid? parentID = null;
            if (form["parentID"].GuidTryParse(out tmpGuid))
                parentID = tmpGuid;

            string categoryName = form["categoryName"];
            string categoryIntro = form["categoryIntro"];
            string categoryDetail = form["categoryDetail"];
            string categoryImageUrl = form["categoryImageUrl"];

            string entityName = form["entityName"];
            string keywords = form["keywords"];
            string description = form["description"];

            string strMode = form["Mode"];
            CategoryMode mode = (CategoryMode)Enum.Parse(typeof(CategoryMode), strMode, true);

            string url = form["url"];

            bool isCommend;
            if (String.IsNullOrEmpty(form["isCommend"]) || !bool.TryParse(form["isCommend"], out isCommend))
                isCommend = false;
            bool isDisplay;
            if (String.IsNullOrEmpty(form["isDisplay"]) || !bool.TryParse(form["isDisplay"], out isDisplay))
                isDisplay = false;
            bool isAuditing;
            if (String.IsNullOrEmpty(form["isAuditing"]) || !bool.TryParse(form["isAuditing"], out isAuditing))
                isAuditing = false;
            bool allowComment;
            if (String.IsNullOrEmpty(form["allowComment"]) || !bool.TryParse(form["allowComment"], out allowComment))
                allowComment = false;

            CategoryInput category = new CategoryInput
            {
                CategoryID = categoryID,
                ParentID = parentID,
                CategoryName = categoryName,
                CategoryIntro = categoryIntro,
                CategoryDetail = categoryDetail,
                CategoryImageUrl = categoryImageUrl,
                Mode = mode,
                Url = url,
                IsCommend = isCommend,
                IsAuditing = isAuditing,
                AllowComment = allowComment,
                EntityName = entityName,
                Keywords = keywords,
                Description = description
            };

            return category;
        }
    }
}
